//1.第一次思路
// max_prev(i) 表示以第 i 个元素结尾的乘积最大子数组的乘积
// min_prev(i) 表示以第 i 个元素结尾的乘积最小子数组的乘积
class Solution {
public:
    int maxProduct(vector<int>& nums) {
        int n = nums.size();
        int result = nums[0];
        int max_prev = nums[0], min_prev = nums[0];

        for(int i = 1; i < nums.size(); ++i) {
            if(nums[i] > 0) {
                max_prev = max(nums[i], max_prev* nums[i]); // 要么新立门户，要么延续
                min_prev = min(nums[i], min_prev* nums[i]);
            }
            else if(nums[i] < 0) {
                int temp = min_prev; //避免覆盖
                min_prev = min(nums[i], max_prev* nums[i]);
                max_prev = max(nums[i], temp* nums[i]);
            }
            else {
                max_prev = 0;
                min_prev = 0;
            }
            result = max(result, max_prev);
        }
        return result;
    }
};


//2.浓缩版本
class Solution {
public:
    int maxProduct(vector<int>& nums) {
        int n = nums.size();
        int result = nums[0];
        int max_prev = nums[0], min_prev = nums[0];

        for(int i = 1; i < n; ++i) {
            int max_old = max_prev, min_old = min_prev;
            max_prev = max({nums[i], max_old * nums[i], min_old * nums[i]});
            min_prev = min({nums[i], max_old * nums[i], min_old * nums[i]});
            result = max(result, max_prev);
        }

        return result;
    }
};


